package com.ruike.alisurface.ui.mainPage;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cunoraz.gifview.library.GifView;
import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.Ttys3Utils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.http.AppUpdateHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.services.AppRunMonitoringService;
import com.ruike.alisurface.services.MyIntentService;
import com.ruike.alisurface.services.TimeOutBroadcastReceiver;
import com.ruike.alisurface.ui.setting.StopSellingActivity;
import com.ruike.alisurface.utils.DataCleanManager;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_frame.manager.FActivityManager;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;
import static com.ruike.alisurface.utils.ShareKey.IS_OID;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;
import static com.ruike.alisurface.utils.ShareKey.Type_sendPlankVersion;

/**
 * Author: voodoo
 * CreateDate: 2020-03-26 026 下午 12:45
 * Description: APP启动页
 */
public class SystemStartActivity extends BaseAty {

    @BindView(R.id.systemStart_pageBg_rlayout)
    RelativeLayout pageBgRlayout;
    @BindView(R.id.systemStart_show_gifv)
    GifView showGifv;
    @BindView(R.id.systemStart_status_tv)
    TextView statusTv;
    @BindView(R.id.systemStart_sn_tv)
    TextView snTv;
    @BindView(R.id.systemStar_sn_code)
    ImageView sn_code;

    boolean isInit = false; // 已经初始化
    private String baseUserId = ShareUtils.getInstance().getString(BASEUSERID, "RK_test"); // 用户类型，默认是未分配用户
    TimeOutBroadcastReceiver mTimeOutBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_system_start;
    }

    @Override
    protected void initViews() {
        L.i("启动页==" + this.getClass().getName());
        showGifv.setVisibility(View.VISIBLE);
        statusTv.setText(new StringBuffer(getResources().getString(R.string.checkingNetworkStr)));
        snTv.setText(new StringBuffer(getResources().getString(R.string.deviceSnStr)).append(DeviceUtils.getDeviceSn()));
        L.i("机器序列号:" + DeviceUtils.getDeviceSn() + "      硬件名:" + Build.FINGERPRINT);
    }

    @Override
    protected void initData() {
        writeShareFile(); // 写入共享文件数据

        String todoDay = TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd");

        // 设置默认 开始重启日期
        if (!ShareUtils.getInstance().containsKey(ShareKey.OFFLINE_RESTART_DAY)) {
            ShareUtils.getInstance().putString(ShareKey.OFFLINE_RESTART_DAY, todoDay);
            L.i("设置默认  重启日期:", "设置重启日期" + todoDay);
        } else {
            String timeday = ShareUtils.getInstance().getString(ShareKey.OFFLINE_RESTART_DAY);
            if (!timeday.equals(todoDay)) {
                L.i("设置默认  重新设置重启日期:", timeday + "===天数不一致，可以设置重置重启次数 10===" + todoDay);
                ShareUtils.getInstance().putInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, 10);
                ShareUtils.getInstance().putString(ShareKey.OFFLINE_RESTART_DAY, todoDay);
                ShareUtils.getInstance().putBoolean(ShareKey.IS_NETWORK_STATUS, false);
            }
        }

        Intent intent = new Intent("com.MainApp.Action.Start"); // 发送主程序启动的广播
        sendBroadcast(intent);
        setDataSNcode(sn_code);
        startService(new Intent(this, AppRunMonitoringService.class)); // 启动APP运行检测服务
        startService(new Intent(this, MQTTService.class)); // 启动Mqtt服务
        Intent itosdkIntent = new Intent(this, MyIntentService.class);
        startService(itosdkIntent);

        // 如果不存在key，则设将key和默认售卖的标志存进去
        if (!ShareUtils.getInstance().containsKey(ShareKey.IS_STOP_SELLING)) {
            ShareUtils.getInstance().putBoolean(ShareKey.IS_STOP_SELLING, false);
        }
        boolean isOfflineRestartApp = ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP, true); // 断网重启app
        L.i("断网重启app" + isOfflineRestartApp);
        if (isOfflineRestartApp) {
            ShareUtils.getInstance().putBoolean(ShareKey.IS_OFFLINE_RESTART_APP, true);
        } else {
            ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP, false);
        }

        // 设置默认购买数量
        if (!ShareUtils.getInstance().containsKey(ShareKey.PURCHASE_COUNT)) {
            ShareUtils.getInstance().putInt(ShareKey.PURCHASE_COUNT, Constant.DefaultData.PURCHASE_COUNT);
        }
        // 设置默认货道显示
        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 0) == 0) {
            ShareUtils.getInstance().putInt(ShareKey.IS_SHOP_TYPE, 1);
        }
        // 设置默认 无广告
        if (ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) == Constant.ADV_TYPE_NONE) {
            ShareUtils.getInstance().putInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE);
        }

        // 设置默认 隐藏底部导航栏
        if (!ShareUtils.getInstance().containsKey(ShareKey.IS_SHOW_NAVIGATION_BAR)) {
            ShareUtils.getInstance().putBoolean(ShareKey.IS_SHOW_NAVIGATION_BAR, false);
        }

        sn_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                todoHome();
            }
        });


        // 获取IS_STOP_SELLING，如果停止售卖状态则跳转至相应界面，停止之后的所有操作
        if (ShareUtils.getInstance().getBoolean(ShareKey.IS_STOP_SELLING)) { // 停止售卖
            startActivity(StopSellingActivity.class, null);

        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 2000;// 规定有效时间
    long[] mHits = new long[COUNTS];//次数数组

    // 多次连续点击  回到桌面
    protected void todoHome() {
        // 每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        // 为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS]; // 重新初始化数组
            L.i("主动退出APP ");
            Intent intent = new Intent("com.MainApp.Action.Exit"); // 发送APP退出的广播
            intent.setComponent(new ComponentName("com.voodoo.appdaemon", "com.voodoo.appdaemon.MyReceiver")); // 括号里为包名+广播类
            sendBroadcast(intent);
            stopService(new Intent(SystemStartActivity.this, AppRunMonitoringService.class));
            mTimeOutBroadcastReceiver.unitTimePrompt(this);
            mTimeOutBroadcastReceiver.infoRest();
            FActivityManager.getInstance().killAllActivityExit();

        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        isInit = true;
    }


    @Override
    public void onNetChange(int netMobile, boolean isConnect) {
        statusTv.setText(isConnect ? getResources().getString(R.string.networkConnectionSuccessStr) : getResources().getString(R.string.networkConnectionFailureStr));
        if (isConnect && isInit) {

            isInit = false;
            statusTv.setText(getString(R.string.system_init_data));
            new MyCountDownTimer(2000, 2000) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    handler.sendEmptyMessage(0x10);

                }
            }.start();
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        try {
            JSONObject object = new JSONObject(requestJsonStr);
            String data = object.optString("data");

            if (requestUrl.endsWith("getAppVersion")) { // 获取APP的版本
                JSONArray jsonArray = new JSONArray(data);
                JSONObject o = (JSONObject) jsonArray.get(0);
                String version = o.getString("Version");
                L.i("onSuccess:程序版本号： " + version);
                ShareUtils.getInstance().putString(ShareKey.VERSION_NUM, version);
                return;
            }
            if (requestUrl.contains("geMchBySn")) {  // 根据机器SN获取机器号MchId
                JSONObject mchObject = new JSONObject(data);
                String idStr = mchObject.optString("Id");
                ShareUtils.getInstance().putString(ShareKey.MCH_ID, idStr);
                L.i("onsuccess: MchId：" + idStr);
                String service_tel = mchObject.optString("service_tel");
                if (!service_tel.equals("null") && service_tel != null && !service_tel.isEmpty()) {
                    L.i("===service_tel==" + service_tel);
                    ShareUtils.getInstance().putString(SERVICE_TEL, service_tel);
                } else {
                    ShareUtils.getInstance().putString(SERVICE_TEL, getString(R.string.noPhoneStr));
                }
                baseUserId = mchObject.optString("BaseUserId");
                ShareUtils.getInstance().putString(BASEUSERID, baseUserId);
                L.i("==BaseUserId==" + baseUserId);
                int IC2_max_lattices = mchObject.optInt("IC2_max_lattices");
                L.i("==货道柜设置余数==" + IC2_max_lattices);
                if (IC2_max_lattices > 0) {
                    ShareUtils.getInstance().putInt(IC2_SLOT_NUM, IC2_max_lattices);
                }
                String logo = mchObject.optString("Logo");
                L.i("==logo==" + logo.length(),logo);
                if (!"null".equals(logo) &&  !TextUtils.isEmpty(logo)) {
                    ShareUtils.getInstance().putString(ShareKey.LOGO, logo);
                }
                boolean is_old = mchObject.optBoolean("is_old");
                ShareUtils.getInstance().putBoolean(IS_OID, is_old);
                L.i("== 不需要查询版本信息=is_old=" + is_old);
                Ttys3Utils.getInstance().LEDSetting(10, "0", "1", "1", 70, 15);
                SystemClock.sleep(600);
                if (!is_old) {
                    Ttys3Utils.getInstance().sendCheckWKVersion(6);
                    SystemClock.sleep(600);
                    Ttys3Utils.getInstance().sendCheckVersion(10);
                }
                AppUpdateHttp.tellServiceAppVersionInfo(this);
                doNext();
                return;
            }

            if (requestUrl.endsWith("TellService_AppVersion_Info")) { // 上报当前APP版本信息
                // 暂无需处理上报后回传的信息
                return;
            }

        } catch (JSONException e) {
            L.i("onSuccess:JSON 字符串异常，一般不会在此出现该问题： " + e.toString());
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x10) {
                statusTv.setText("尝试请求中");
                MchApiHttp.getMchBySn(SystemStartActivity.this); // 获取机器信息
            }
        }
    };

    /**
     * 下一步
     */
    private void doNext() {

        if (baseUserId.equals("RK_test")) {
            startActivity(BindMachineActivity.class, null);
            finish();
            return;
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startCountdownTimer(0, null, null);
            }
        }, 2000);
//        startCountdownTimer(3, null, null);
    }


    @Override
    public void onError(String url, String errorMsg) {
        super.onError(url, errorMsg);
        if (url.endsWith("getAppVersion")) { // 获取APP的版本
            statusTv.setText(getString(R.string.notGetVersionStr));
            return;
        }

        if (url.contains("geMchBySn")) {  // 根据机器SN获取机器号MchId
            statusTv.setText(errorMsg);
            L.i(" 再次尝试请求数据== " + errorMsg);
            handler.sendEmptyMessageDelayed(0x10, 10000);
            return;
        }

        if (url.endsWith("TellService_AppVersion_Info")) { // 上报当前APP版本信息
            // 暂无需处理上报后回传的信息
            return;
        }
    }

    /**
     * 写入共享文件
     */
    private void writeShareFile() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mainPackageName", BuildConfig.APPLICATION_ID); // 程序包名
            jsonObject.put("mainPackageType", Constant.APP_TYPE); // 程序类型
            L.i("写入共享文件", "文件地址：" + Constant.MAIN_PACKAGE_NAME_FILE_PATH, "写入内容：" + jsonObject.toString());

            handler.post(new Runnable() {
                @Override
                public void run() {
                    FileUtils.writeFileFromString(Constant.MAIN_PACKAGE_NAME_FILE_PATH, jsonObject.toString(), false);
                    FileUtils.CteateFileFromString(Environment.getExternalStorageDirectory()
                            + File.separator + "picture" + File.separator + "adv");
                    FileUtils.CteateFileFromString(Environment.getExternalStorageDirectory()
                            + File.separator + "picture" + File.separator + "goods_img");
                    FileUtils.CteateFileFromString(Environment.getExternalStorageDirectory()
                            + File.separator + "picture" + File.separator + "Vedio");
                    FileUtils.CteateFileFromString(Constant.topAdvpath);
                    FileUtils.CteateFileFromString(Constant.alAdvpath);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    int checkVersion = 0;//处理多次查询板子导致的异常

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_sendPlankVersion)) {
            String msg = event.getMessage();
            L.i("tjf-sendPlankVersion--", msg);
            String[] pb = msg.split("-");
            /*"MV", "Fir", "Sec", "Thr" "T"*/
            if (pb[0].equals("MV")) {
                if (checkVersion < 1) {
                    ShareUtils.getInstance().putString("MV", pb[1]);
                    checkVersion++;
                    if (!"140C07140B0F".equals(pb[1]) && !"14040F130C05".equals(pb[1])) {
                        Ttys3Utils.getInstance().sendCheckVersion(11);
                    } else {
                        L.i("tjf-当前版本不查询副柜信息--", "140C07140B0F==" + msg);
                    }
                }
            } else if (pb[0].equals("Fir")) {
                ShareUtils.getInstance().putString("Fir", pb[1]);
                Ttys3Utils.getInstance().sendCheckVersion(12);
            } else if (pb[0].equals("Sec")) {
                ShareUtils.getInstance().putString("Sec", pb[1]);
                Ttys3Utils.getInstance().sendCheckVersion(13);
            } else if (pb[0].equals("Thi")) {
                ShareUtils.getInstance().putString("Thr", pb[1]);
            }
        }
    }


    /**
     * 重启自身APP
     */
    public void reStartApp() {
        Intent intent = new Intent(this, SystemStartActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    @Override
    protected void onResume() {
        super.onResume();
        DataCleanManager.cleanExternalFiles();
        showGifv.play();
        mTimeOutBroadcastReceiver = new TimeOutBroadcastReceiver();
        mTimeOutBroadcastReceiver.initTimePrompt(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mTimeOutBroadcastReceiver.unitTimePrompt(this);
        mTimeOutBroadcastReceiver = null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        showGifv.pause();
        L.i("onStop.showShop--", Constant.showShop);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            L.i("onDestroy--handler 移除消息");
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
